<?php

class CommentsController extends CommentsAppController
{
	var $name = 'Comments';
	var $helpers = array('Html', 'Form', 'Time', 'Javascript');
	var $components = array('Session','Email');
	var $paginate = array('limit' => 20,'order'=>array('Comment.added'=>'desc')); 
		
	function beforeFilter()
	{
		$this->Comment = $this->{$this->modelNames[0]};
		if(!isset($this->CommentAlias))
		{
			$this->CommentAlias = $this->modelNames[0];
		}
		parent::beforeFilter();		
	}
	function beforeRender()
	{
		if($this->name != 'Comments')
		{
			$viewPaths = am(Configure::read('viewPaths'), COMMENTS_PATH.'views'.DS);
			Configure::write('viewPaths', $viewPaths);
		}
		parent::beforeRender();
	}

	function add($item_id=null)
	{
		if(empty($item_id))
		{
			$this->errorMsg(__('Invalid URL.'));
			$this->redirect($this->referer());
		}
		
		if($this->data)
		{			
			$userModel = $this->getAuthModel();
			$this->Comment->create();
			if(!isset($this->data['Guest']))
			{
				$userkey = Inflector::underscore($userModel).'_id';
				$this->data[$this->Comment->alias][$userkey] = $this->getAuthModel('id');
			}	
			if($this->Comment->saveAll($this->data,array('validate'=>'first')))
			{
				$this->successMsg(__('The comment has been saved.', true));
				$this->afteradd($this->Comment->getLastInsertId(),$item_id);
			}
			else
			{
				$this->errorMsg(__('Unable to add your comment. Please try again.',true));
				$this->redirect($this->referer());
			}
		}		
		$this->set('item_id',$item_id);
	}

	function add_old($type=null, $item_id=null)
	{
		if(empty($type) || empty($item_id))
		{
			$this->errorMsg(__('Invalid URL.'));
			$this->redirect($this->referer());
		}
		if($this->data)
		{
			
			$userModel = $this->Session->read('Auth.model');
			$mainModel = cri($type);
			//$this->Comment = $mainModel->getCommentModel();
			$this->Comment->create();
			if(isset($this->data['Guest']))
			{
				$this->requestAction('/users/guests/add');
			}			

			$key = Inflector::underscore($userModel).'_id';

			$this->data[$this->Comment->alias][$key] =			
			$this->Session->read('Auth.'.$userModel.'.id');

			$this->data[$this->Comment->alias][$mainModel->foreignKey] = $item_id;
			
			if($this->Comment->save($this->data))
			{
				$this->successMsg(__('The comment has been saved.', true));
				callHooks('afterCommentAdded','.+',$this,$item_id);
				$this->redirect($this->referer());
			}
			else
			{
				$this->errorMsg(__('Unable to add your comment. Please try again.',true));
				$this->redirect($this->referer());
			}
		}
		$this->set('item_id',$item_id);
		$this->set(compact('item_id','type'));
	}
	
	/* @todo Refactor
	function edit($id)
	{
		$this->restrictUserType('Moderator','Admin');
		if($id!=null)
		{
			if(empty($this->data))
			{
				$this->data = $this->Comment->read(null,$id);
				$this->Session->write('redirectTo',$this->referer());
			}
			elseif(!empty($this->data))
			{
				$this->Comment->id = $id;
				if($this->Comment->save($this->data))
				{
					$this->Session->setFlash('Comment has been edited');
					$this->redirect($this->Session->read('redirectTo'));
				}
			}
		}else
			$this->redirect('/');

	}*/

	function admin_changeStatus($status=null,$id = null)
	{
		$this->Comment->recursive = -1;
		$commentData = $this->Comment->findById($id);
		if(empty($commentData) || empty($status))
		{
			$this->errorMsg(__('Invalid Request!'));
			$this->redirect('/admin');
		}
		else
		{
			$statusValue = '0';
			if($status == 'publish')
			{
				$statusValue = '1';
			}
			$this->Comment->id = $id;
			if($this->Comment->saveField('status',$statusValue))
			{
				//@FIXME
				$statusToShow = $status.'ed'; 
				$this->successMsg(sprintf(__('%s has been %s'),$this->CommentAlias,$statusToShow));
				
				if($status == 'publish')
				{
					callHooks('afterCommentPublish','.+',$this,$id);
				}
			}else
			{
				$this->errorMsg(__('Sorry, status could not be changed.'));
			}
			
			
			$this->redirect($this->referer());
		}

	}

	function delete($id)
	{
		$this->restrictUserType('Moderator','Admin');
		if($id!=null)
		{
			$this->Comment->del($id);
			$this->redirect($this->referer());
		}
		$this->cakeError('error404');
	}

	function userComments($type='all',$user_id=null)
	{
		$this->helpers[] = 'Effects.Navigation';
		$this->helpers[] ='Cms.Image';
		if(!$user_id)
		{
			if($this->Session->read('Auth.User.id'))
			{
				$user_id = $this->Session->read('Auth.User.id');
				$this->pageTitle='My Comments';
			}else
			{
				$this->Session->setFlash('Please login to view this page');
				$this->redirect($this->Auth->loginRedirect.'/redirectBack:true');
			}
		}
		$userObj->recursive = 0;
		$userObj = ClassRegistry::init('Users.User');
		$user = $userObj->read(null,$user_id);
		if($user['User']['id']!=$this->Session->read('Auth.User.id'))
			$this->pageTitle = 'Comments of '.$user['User']['name'].' made on blog';
		$this->Comment->recursive = 0;
		if($type =='all')
			$condition =''; 
		else
		{
			$this->checkPluginAccess(ucfirst($type));
			$condition =' AND Comment.type ="'.ucfirst($type).'"';
		}
		$this->set('user',$user);
		$this->set('Comments', $this->paginate(array('Comment.user_id ='.$user_id.$condition)));
	}

	function admin_index($type = false)
	{ 
		$this->helpers[] ='Users.UserContent';
		$this->set('page_heading', "Comments");
		if($type)
			$this->set('type', $type);
		$this->Comment->bindModel(
								array(
								'User'=>array(
											'className'=>'Users.User',
											'foreignKey'=>'user_id',
											'conditions'=>'Comment.type="Content"'
											)
									)	
								,false);
		//$this->Comment->recursive = 0;
		$this->set('comments', $this->paginate());
	}

	function admin_moderate($type = false, $spam = false)
	{
		$this->set('page_heading', "Comments of ".$type);
		if($type)
			$this->set('type', $type);
		$this->Comment->recursive = 0;

		if($spam)
			$this->set('comments', $this->paginate(array('Comment.type'=>$type, 'Comment.status'=>UC_STATUS_SPAM )));
		else
			$this->set('comments', $this->paginate(array('Comment.type'=>$type, 'Comment.status'=>UC_STATUS_PENDING )));

		$this->set(compact('data'));
	}

	function admin_edit($id = null) 
	{
		if(empty($this->data))
		$this->Session->Write('goto',$this->referer());
			
	
		$type=$this->Session->Read('commentType');
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Comment', true));
			$this->redirect(array('action'=>'manageComment'));
		}
		
		if (!empty($this->data)) {
			if ($this->Comment->save($this->data)) {
				$this->Session->setFlash(__('The Comment has been modified', true));
				$this->redirect($this->Session->Read('goto'));
			} 
			else 
			{
				$this->Session->setFlash(__('The Comment could not be modified. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Comment->read(null, $id);
		}
	}
	//filter post to date/month/year wise
	function admin_filterDate()
	{	
		if(array_key_exists('filter',$this->params['named']))
		$filter = $this->params['named']['filter'];
		else
			$filter=null;
		
		if($filter!=null)
		{	
			$criteria="Comment.type='Post'";
			switch($filter)
			{
				case 'today':
					$criteria="Comment.added=CURDATE() AND Comment.type='Post'";
					break;
				
				case 'oneWeek':
					$criteria="YEARWEEK(Comment.added,2)= YEARWEEK(CURDATE(),2) AND Comment.type='Post'";
					break;

				case 'oneMonth':
				$criteria="DATE_FORMAT(Comment.added,'%m-%y')= DATE_FORMAT(CURDATE(),'%m-%y') AND Comment.type='Post'";
					break;

				case 'oneYear':
				$criteria="DATE_FORMAT(Comment.added,'%y')= DATE_FORMAT(CURDATE(),'%y') AND Comment.type='Post'";
					break;
			}
			$this->_bindUserAndPost();
			$this->set('filter',$filter); 
			$this->Post->recursive = 0;
			$this->paginate=array('limit'=>10);
			$this->set('comments',$this->paginate(array($criteria)));
			$this->render('admin_manage_comment');

		}
	}

	//serach post with given body and title
	function admin_search()
	{
		$this->_bindUserAndPost();
		$criteria='';
		$search=$this->data['Comment']['keyword'];
		if(!empty($search) OR (!isset($this->data['Comment']['keyword'])))
		{
			$search=$this->data['Comment']['keyword'];
			$criteria = "(Comment.body LIKE ('%".$search."%')
			OR Post.title LIKE ('%".$search."%')) AND Comment.type='Post'";
			$this->Post->recursive = 0;
			$this->set('comments',$this->paginate(array($criteria)));
			
		}
		$this->render('admin_manage_comment');
	}
	
	function admin_view($id = false)
	{
		$this->set('page_heading', "View Comments");
		$this->Comment->bindModel(array('belongsTo'=>array('User'=>array('className'=>'Users.User'))),false);
		$this->Comment->bindModel(array('belongsTo'=>array('Content'=>array('className'=>'Content','foreignKey'=>'item_id','conditions'=>'Comment.type = "Content"'))),false);
		$comment_data = $this->Comment->findById($id);
		$this->set('comment_data', $comment_data);
	}

	//bind user and post model, used in manage post and comments
	function _bindUserAndPost()
	{
		$this->Comment->bindModel(array('belongsTo'=>array('User'=>array('className'=>'Users.User'))),false);
		
		$this->Comment->bindModel(array('belongsTo'=>array('Post'=>array('className'=>'Blog.Post','foreignKey'=>'item_id','condition'=>'Comment.type="Post"'))),false);
	}

	//used for indix comment
	function admin_manageComment()
	{	
		$this->_bindUserAndPost();
		$comments=$this->paginate('Comment',array('Comment.type'=>'Post'));	
		$this->set('comments',$comments);
				
	}

	function admin_delete($id = null) 
	{
		$comment = $this->Comment->findById($id);
		if(empty($comment)) 
		{
			$this->errorMsg(__('Invalid id for comment', true));
		}
		if($this->Comment->del($id)) 
		{
			$this->successMsg(sprintf(__('%s has been deleted.', true),$this->CommentAlias));
		}else
		{
			$this->successMsg(sprintf(__('Sorry, %s could not be deleted.', true),$this->CommentAlias));	
		}
		$this->redirect($this->referer());
	}

		function showAll($userName=null)
		{
			if($userName)
				$id = ClassRegistry::init('Users.User')->field('id',array('username'=>$userName));
			else
			{
				$id = $this->Session->read('Auth.User.id');
				$userName = $this->Session->read('Auth.User.username');
			}

			$contentModel = ClassRegistry::init('Content');
			$this->Comment->bindModel(array('belongsTo'=>array('Content'=>array('foreignKey'=>'item_id'))),false);

			$this->Comment->bindModel(array('belongsTo' => array('User'=>array('className'=>'Users.User'))),false);
			
			$movieIds = $contentModel->find('list',array('fields'=>array('Content.id'),'conditions'=>array('Content.type'=>'Movie')));
			
			$this->paginate['conditions']=array('Comment.type'=>'Content','Comment.user_id'=>$id,'Comment.status'=>1,array('NOT'=>array('Comment.item_id'=>$movieIds)));
			$this->paginate['recursive']=1;
			$this->paginate['limit']=10;
			$comments = $this->paginate();
			$this->set('comments',$comments);
			$this->set('id',$id);
			$this->set('userName',$userName);
		}

		function afteradd($lastInsertId,$itemId)
		{
			//callHooks('afterCommentAdd','.+',$this,$itemId);

		}

		/**
			add addGuest in children to modify
		**/
		function addGuest()
		{
			$this->requestAction('/users/guests/add');
		}

}
?>